/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.imsx.controller.util;

import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.DBAddress;
import com.mongodb.Mongo;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author mivkys
 */
public final class Conexion {
    private static final int [] _ports = { 27017, 27018, 27019 };
    public static void conect() throws UnknownHostException, InterruptedException{
        final BasicDBObject config = new BasicDBObject("_id", "test");

        final List<BasicDBObject> servers = new ArrayList<BasicDBObject>();

        int idx=0;
        for (final int port : _ports) {
            final BasicDBObject server = new BasicDBObject("_id", idx);
            server.put("host", ("127.0.0.1:" + port));

            if (idx > 0 && idx != 3) {
                //server.put("priority", 0);
                //server.put("slaveDelay", 1);
            }

            if (idx == 2) server.put("arbiterOnly", true);

            servers.add(server);

            idx++;
        }

        config.put("members", servers);

        final Mongo mongo = new Mongo(new DBAddress("127.0.0.1", 27017, "admin"));

        final CommandResult result
        = (CommandResult) mongo.getDB("amazondb").command(new BasicDBObject("replSetInitiate", config));

        System.out.println(result);

        // Sleep for a bit to wait for all the nodes to be intialized.
        Thread.sleep(5000);
    }
}
